package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.mob.MobSDK;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.MyWebViewClient;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

import java.io.IOException;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;

/**
 * 使用WebView播放视频时需要注意的地方： 1、加网络访问权限（及其他所需要的权限）；
 * 2、WebViewClient中方法shouldOverrideUrlLoading可用来实现点击webView页面的链接；
 * 3、WebView中播放视频需要添加webView.setWebChromeClient(new WebChromeClient())；
 * 4、视频竖屏时，点击全屏，想要切换到横屏全屏的状态，那么必须在Manifest.xml配置文件该Activity的
 * 配置文件中添加android:configChanges="orientation|screenSize"语句。
 * 5、如果视频不能播放，或者播放比较卡，可以采用硬件加速，即在Application，或所在的Activity的配置文件中添加
 * android:hardwareAccelerated="true"即可。
 * 
 * @author zhongyao
 */
@SuppressLint("SetJavaScriptEnabled")
public class TestThirdActivity extends BaseJpStarActivity {
	private WebView webView;
	private WebView webView2;
	private FrameLayout video_fullView;// 全屏时视频加载view
	private View xCustomView;
	private ProgressDialog waitdialog = null;
	private CustomViewCallback xCustomViewCallback;
	private ProgressBar mprogressBar;
	private TextView tv_html_title;
	private TextView tv_word_back;
	private MediaPlayer mPlayer;

	@SuppressLint("JavascriptInterface")
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.activity_fuxi);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}
		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintResource(R.color.base_color);

		boolean isfirst = getIntent().getBooleanExtra("isfirst", true);

		mprogressBar = (ProgressBar) findViewById(R.id.mProgress);

		tv_html_title = (TextView) findViewById(R.id.tv_html_title);
		tv_word_back = (TextView) findViewById(R.id.tv_word_back);
		tv_word_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		webView = (WebView) findViewById(R.id.webView);
		webView2 = (WebView) findViewById(R.id.webView2);
		lESSON_ID = getIntent().getStringExtra("LESSON_ID");
		String LESSON_NAME = getIntent().getStringExtra("LESSON_NAME");
		
		WebSettings settings = webView.getSettings();
		WebSettings settings2 = webView2.getSettings();

		settings.setJavaScriptEnabled(true);
		webView2.getSettings().setJavaScriptEnabled(true);
		webView2.getSettings().setBuiltInZoomControls(false);
		webView2.getSettings().setUseWideViewPort(true);
		webView2.getSettings().setRenderPriority(RenderPriority.HIGH);
		webView2.getSettings().setDatabaseEnabled(true);
		webView2.getSettings().setDomStorageEnabled(true);
		webView2.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		webView2.getSettings().setPluginState(PluginState.ON);
		webView2.loadData("", "text/html", null);

		webView.getSettings().setAllowFileAccess(true);
		webView2.setWebViewClient(new MyWebViewClient(mprogressBar));
		webView2.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				// TODO Auto-generated method stub
				mprogressBar.setProgress(newProgress);
			}
		});

		int VERSION_SDK_ELEVEN = 14;
		webView.setVisibility(View.GONE);

		webView2.addJavascriptInterface(new WebAppInterface(this), "Android");
//		webView2.loadUrl(Constant.SERVER_tk + ":36356/jpjNewPage/question.html");


		webView2.loadUrl("https://moregolden.com:25697/question.html");
		// webView2.loadUrl(NetConstant.H5
		// + "html5/AndroidPage/Android_pageInfo.html");

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

		if (mediaPlayer != null) {

			mediaPlayer.pause();
		}

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		final Request request = new Request.Builder().url(
				NetConstant.USERONLINE + "SaveInterfaceEnd.aspx?msg=1&rid="
						+ rid + "&account="
						+ SPUtils.getString(this, ConfigConstant.USERNAME))
				.build();
		// new call
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(callBackTimefinish);

		// TestThirdActivity.this.finish();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		webView2.setVisibility(View.GONE);
		webView.removeAllViews();
		webView.destroy();
		webView2.removeAllViews();
		webView2.destroy();
		if (webView != null) {
			webView = null;
		}
		if (webView2 != null) {
			webView2 = null;
		}
		System.gc();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		final Request request = new Request.Builder().url(
				NetConstant.USERONLINE
						+ "InitInterfaceBegin.aspx?msg=1&type=1&account="
						+ SPUtils.getString(this, ConfigConstant.USERNAME)
						+ "&gradeid=" + gradeid + "&lessonid=" + lESSON_ID)
				.build();
		// new call
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(callBackTime);
	}

	private WebChromeClient chromeClient = new WebChromeClient() {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress == 100) {
				
			}
		}
	};

	private WebViewClient client = new WebViewClient() {
		// 当页面加载完成之后会调用此方法
		@Override
		public void onPageFinished(WebView view, String url) {
			
		}
	};

	public int getPhoneSDKInt() {
		int version = 0;
		try {
			version = Integer.valueOf(Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return version;
	}

	private String rid;
	Callback callBackTime = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			String json = arg0.body().string();
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			// Log.i("testtime", "课后检测开始");
			// Log.i("testtime", json.toString());

			Gson gson = new Gson();
			timeresq fromJson = gson.fromJson(json, timeresq.class);
			rid = fromJson.rid;
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}
	};
	
	Callback callBackTimefinish = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}
	};
	
	private String lESSON_ID;

	private MediaPlayer mediaPlayer = new MediaPlayer();

	public class WebAppInterface {
		Context mContext;

		/** Instantiate the interface and set the context */
		WebAppInterface(Context c) {
			mContext = c;
		}

		/** Show a toast from the web page */
		@JavascriptInterface
		public void showToast(String toast) {
			if (mediaPlayer == null) {

				mediaPlayer = new MediaPlayer();
			}
			String uri;
			// Toast.makeText(mContext, toast, 0).show();
			if ("http".equals(toast.substring(0, 4))) {
				uri = toast;
			} else {
				uri = NetConstant.H5 + "html5/" + toast;
			}

			mediaPlayer.reset();

			try {
				mediaPlayer.setDataSource(uri);
				mediaPlayer.prepare();
				mediaPlayer.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// prepare之后自动播放

		}

		// 传递参数
		@JavascriptInterface
		public String getParam() {

			String param = SPUtil.getString(mContext, ConfigConstant.USERNAME,
					"")
					+ ",1,"
					+ lESSON_ID
					+ ","
					+ SPUtil.getString(mContext, "role", "");
			Log.e("test", "param=" + param);
			return param;
		}

		// 关闭界面
		@JavascriptInterface
		public void finish() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					TestThirdActivity.this.finish();
				}
			});
			Log.e("test", "finish");
			return;
		}

		// 重新做题
		@JavascriptInterface
		public void againtest() {

			Log.e("test", "againtest");

			new Thread(new Runnable() {
				@Override
				public void run() {

					Intent intent = new Intent(mContext,
							TestThirdActivity.class);
					intent.putExtra("LESSON_ID", lESSON_ID);
					mContext.startActivity(intent);

				}
			}).start();
			TestThirdActivity.this.finish();
			return;
		}

		// 分享界面
		@JavascriptInterface
		public void share(final String total) {

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					String[] StrArray = total.split("&");
					clickShare(StrArray[3], StrArray[4]);
					Log.e("test", "total=" + total);

				}
			});
			// moduleType=0&userType=2&exam_type=2&time=144&mark=80&num=13006314760
			return;
		}


		// 播放正误音频
		@JavascriptInterface
		public void playertrueorfalse(int num) {
			Log.i("test",num+"num");

			if (mPlayer != null) {
				mPlayer.release();
				mPlayer = null;
			}
			if(num==1){

				mPlayer = MediaPlayer.create(TestThirdActivity.this, R.raw.rightmp3);
			}else if(num==2){

				mPlayer = MediaPlayer.create(TestThirdActivity.this, R.raw.errormp3);
			}
			mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					if (mPlayer != null) {
						mPlayer.release();
						mPlayer = null;
					}
				}
			});
			mPlayer.start();
			return;
		}
	}

	private void clickShare(final String totaltime, final String Score) {

		// TODO Auto-generated method stub
		MobSDK.init(TestThirdActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用

					String url = Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
							+ totaltime
							+ "&"
							+ Score
							+ "&num="
							+ SPUtils.getString(TestThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=1";
					String title = SPUtils.getString(TestThirdActivity.this,
							"name")
							+ "在"
							+ "自主检测"
							+ "环节花费了"
							+ totaltime.substring(5, totaltime.length())
							+ "秒获得" + Score.substring(5, Score.length()) + "分,为你点赞！";
					int unicodeJoy = 0x1F44D;
					String emojiString = new String(Character
							.toChars(unicodeJoy));
					paramsToShare
							.setTitleUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
									+ totaltime
									+ "&"
									+ Score
									+ "&num="
									+ SPUtils.getString(TestThirdActivity.this,
											ConfigConstant.USERNAME)
									+ "&exam_type=1");
					paramsToShare.setTitle(SPUtils.getString(
							TestThirdActivity.this, "name")
							+ "在"
							+ "自主检测"
							+ "环节花费了"
							+ totaltime.substring(5, totaltime.length())
							+ "秒获得"
							+ Score.substring(5, Score.length())
							+ "分,为你点赞！");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(title + "\n\r想展现你的实力吗?来这里比拼一下吧！"
							+ url);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare
							.setUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
									+ totaltime
									+ "&"
									+ Score
									+ "&num="
									+ SPUtils.getString(TestThirdActivity.this,
											ConfigConstant.USERNAME)
									+ "&exam_type=1");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare
							.setSiteUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
									+ totaltime
									+ "&"
									+ Score
									+ "&num="
									+ SPUtils.getString(TestThirdActivity.this,
											ConfigConstant.USERNAME)
									+ "&exam_type=1");

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare
							.setTitleUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
									+ totaltime
									+ "&"
									+ Score
									+ "&num="
									+ SPUtils.getString(TestThirdActivity.this,
											ConfigConstant.USERNAME)
									+ "&exam_type=1");
					paramsToShare.setTitle(SPUtils.getString(
							TestThirdActivity.this, "name")
							+ "在"
							+ "自主检测"
							+ "环节花费了"
							+ totaltime.substring(5, totaltime.length() )
							+ "秒获得" + Score.substring(5, Score.length() ) + "分,为你点赞！");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("想展现你的实力吗?来这里比拼一下吧！");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare
							.setUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
									+ totaltime
									+ "&"
									+ Score
									+ "&num="
									+ SPUtils.getString(TestThirdActivity.this,
											ConfigConstant.USERNAME)
									+ "&exam_type=1");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare
							.setSiteUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?moduleType=0&userType=0&"
									+ totaltime
									+ "&"
									+ Score
									+ "&num="
									+ SPUtils.getString(TestThirdActivity.this,
											ConfigConstant.USERNAME)
									+ "&exam_type=1");

				}
			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用

		// 启动分享GUI
		oks.show(this);
	}

	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	@Override
	public void finish() {
		ViewGroup view = (ViewGroup) getWindow().getDecorView();
		view.removeAllViews();
		super.finish();
	}

}
